from app import db
from datetime import datetime
import json

class Statistic(db.Model):
    __tablename__ = 'statistics'
    
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.Date, nullable=False, unique=True, index=True)
    focus_count = db.Column(db.Integer, default=0)  # 专注次数
    focus_time = db.Column(db.Integer, default=0)  # 专注总时间（分钟）
    break_count = db.Column(db.Integer, default=0)  # 休息次数
    break_time = db.Column(db.Integer, default=0)  # 休息总时间（分钟）
    completed_goals = db.Column(db.Integer, default=0)  # 完成目标数
    efficiency = db.Column(db.Float, default=0)  # 专注效率（百分比）
    best_time = db.Column(db.String(20), nullable=True)  # 最佳专注时段
    daily_summary = db.Column(db.Text, default='{}')  # 每日摘要（JSON对象）
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def to_dict(self):
        return {
            'id': self.id,
            'date': self.date.isoformat() if self.date else None,
            'focus_count': self.focus_count,
            'focus_time': self.focus_time,
            'break_count': self.break_count,
            'break_time': self.break_time,
            'completed_goals': self.completed_goals,
            'efficiency': self.efficiency,
            'best_time': self.best_time,
            'daily_summary': json.loads(self.daily_summary) if isinstance(self.daily_summary, str) else self.daily_summary,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
        
    def set_daily_summary(self, summary_data):
        """设置daily_summary字段的辅助方法"""
        if summary_data is None:
            self.daily_summary = '{}'
        elif isinstance(summary_data, dict):
            self.daily_summary = json.dumps(summary_data)
        elif isinstance(summary_data, str):
            try:
                # 验证是否为有效的JSON
                json.loads(summary_data)
                self.daily_summary = summary_data
            except:
                self.daily_summary = '{}'
        else:
            self.daily_summary = '{}' 